package main.mysql;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBContext {

	private String Table_Name = "marks";
	private String Create_Marks = "create table " + Table_Name + "("
			+ "id integer primary key autoincrement," + "name text,"
			+ "mark varchar(1)" + ")";

	private String Drop_Marks = "drop table " + Table_Name;

	private SQLiteDatabase db;
	private MyHelper helper;

	public DBContext(Context context) {
		helper = new MyHelper(context);
		db = helper.getWritableDatabase();
	}

	public void createTable() {
		try {
			helper.CreateTable(db, Create_Marks);
		} catch (Exception e) {

		}
	}

	public void deleteTable() {
		helper.CreateTable(db, Drop_Marks);
	}

	public long insert(Model m) {
		ContentValues val = new ContentValues();
		val.put("name", m.getName());
		val.put("mark", m.getMark());

		long id = db.insert(Table_Name, null, val);

		return id;
	}

	public List<Model> getAllModels(String[] columns, String selection,
			String[] selectionArgs, String groupBy, String having,
			String orderBy) {

		List<Model> models = new ArrayList<Model>();
		Cursor c = db.query(Table_Name, columns, selection, selectionArgs,
				groupBy, having, orderBy);

		c.moveToFirst();

		while (!c.isAfterLast()) {
			models.add(getThis(c));
			c.moveToNext();
		}

		return models;
	}

	private Model getThis(Cursor c) {
		Model m = new Model();

		m.setId(c.getInt(0));
		m.setName(c.getString(1));
		m.setMark(c.getString(2).charAt(0));

		return m;
	}

	public void close() {
		db.close();
		helper.close();
	}

}
